// 高德地图
<template>
  <div class="mapPosition-root">
    <div class="top">
      <el-input
        size="small"
        v-model="address"
        @change="changeAddress"
        :disabled="disabled"
        clearable
      ></el-input>
      <div class="gps">
        <div>经度：{{ gpsX }}</div>
        <div class="gps-li">纬度：{{ gpsY }}</div>
      </div>
      <!-- <el-button class="select-map" type="primary" size="mini">获取地址</el-button> -->
    </div>
    <div id="amap"></div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "17591c71b4a683b811879a3c6bbd79b8",
};

export default {
  name: "mapPosition",
  components: {},
  props: {
    initMapData: {
      type: Object,
      default: () => {
        return {
          address: "", // input中的地址文字
          gpsX: "",
          gpsY: "",
        };
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      address: "",
      gpsX: "",
      gpsY: "",
			towncode: "",
    };
  },
  watch: {
    initMapData: {
      handler(newVal, oldVal) {
        if (newVal) {
          // console.log('watch',newVal)
          if(!newVal.gpsX||!newVal.gpsY){
            return;
          }
          this.address = newVal.address;
          this.gpsX = newVal.gpsX;
          this.gpsY = newVal.gpsY;
					this.towncode = newVal.towncode;
          if(!this.map){
            this.initMap();
          }else{
            this.updateMap();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    // if(this.initMapData.address){
    // 	this.address = this.initMapData.address
    // 	this.gpsX = this.initMapData.gpsX
    // 	this.gpsY = this.initMapData.gpsY
    // }
    this.initMap();
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: "847291d6c9f3886a6d0327be1f57d623", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
					console.log('map load',this.map)
          if(!this.map){
            this.map = new AMap.Map("amap", {
              //设置地图容器id
              zoom: 8, //初始化地图级别
            });
          }
          if (this.gpsX && this.gpsY) {
            this.map.setCenter([this.gpsX, this.gpsY]); 
          } else {
            this.gpsX = this.map.getCenter().lng;
            this.gpsY = this.map.getCenter().lat;

            this.regeoCode(this.gpsX, this.gpsY);
          }
          // console.log(this.map.getCenter())
          // this.marker = new AMap.Marker();
          // this.map.add(this.marker);
          this.setMarker(this.gpsX, this.gpsY);

          this.map.on("click", (e) => {
            if(this.disabled){
              return;
            }
            // console.log(e)
            this.gpsX = e.lnglat.getLng();
            this.gpsY = e.lnglat.getLat();
            this.setMarker(this.gpsX, this.gpsY);
            this.regeoCode(this.gpsX, this.gpsY);
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    updateMap() {
      this.map.setCenter([this.gpsX, this.gpsY]);
      this.setMarker(this.gpsX, this.gpsY);
    },
		/**
		 * 根据经纬度在地图上绘制marker
		 */
    setMarker(gpsX, gpsY) {
      // console.log('setmaker')
      if(this.marker){
        this.map.remove(this.marker);
      }
      this.marker = new AMap.Marker();
      this.map.add(this.marker);
      this.marker.setPosition([gpsX, gpsY]);
    },
    /**
     * 逆地理编码，将经纬度转成地址
     */
    regeoCode(gpsX, gpsY) {
			let lnglat = [gpsX, gpsY];

			if(!this.geocoder){
				this.geocoder = new AMap.Geocoder({
					radius: 1000, //范围，默认：500
				});
			}
      this.geocoder.getAddress(lnglat, (status, result) => {
        console.log('result===old',result);
        if (status === "complete" && result.regeocode) {
          this.address = result.regeocode.formattedAddress;
          this.towncode = result.regeocode.addressComponent.towncode;
          this.postEmit();
        } else {
          console.warn("根据经纬度查询地址失败");
        }
      });
    },
    changeAddress(e) {
      this.address = e;
      this.postEmit();
    },
    getCountySubIndex(cityCode){
      // 中山、东莞截取10位
      let filterList = ['442000000000','441900000000']
      if(filterList.findIndex(t=>t==cityCode)>-1){
        return 10;
      }
      return 6;
    },
    postEmit(){
      let areaCode = []
      if(this.towncode){
        console.log('this.towncode==',this.towncode)
        areaCode.push(this.towncode.substr(0,2).padEnd(12,'0'))
        let cityCode = this.towncode.substr(0,4).padEnd(12,'0')
        areaCode.push(cityCode)
        let subIndex = this.getCountySubIndex(cityCode)
        areaCode.push(this.towncode.substr(0,subIndex).padEnd(12,'0'))
      }
      console.log('areaCode==',areaCode)
      let pramas = {
        address: this.address,
        gpsX: this.gpsX,
        gpsY: this.gpsY,
        towncode: this.towncode,
        areaCode,
      };
      this.$emit("changeAddress", pramas);
    },
    reloadMap(){
      console.log('reloadMap')
      this.map = null;
      this.address = '';
      this.gpsX = '';
      this.gpsY = '';
      this.towncode = '';
      this.initMap();
    }
  },
};
</script>

<style lang="scss" scoped>
.mapPosition-root {
  .top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .gps {
      margin-left: 20px;
      display: flex;
      justify-content: left;
      .gps-li {
        margin-left: 20px;
      }
    }
    .select-map {
      margin-left: 20px !important;
    }
  }
  #amap {
    height: 300px;
  }
}

::v-deep .el-input {
  width: 32%;
}
</style>
